package com.founder.utils;

import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import java.net.InetAddress;

/**
 * @author zhunian
 * @create 2018-02-22 21:24
 **/
@Configuration
public class ServiceUtil implements ApplicationListener<ServletWebServerInitializedEvent> {
    private static ServletWebServerInitializedEvent event;

    @Override
    public void onApplicationEvent(ServletWebServerInitializedEvent event) {
        ServiceUtil.event = event;
    }

    public static int getPort() {
        Assert.notNull(event);
        int port = event.getApplicationContext().getWebServer().getPort();
        Assert.state(port != -1, "端口号获取失败");
        return port;
    }

    public static String getIP() {
        String host = "127.0.0.1";
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e){
            e.printStackTrace();
        }
        return  host;
    }
}
